﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using NLog;
using NLog.Config;
using NLog.Layouts;
using NLog.Targets;
using MultiCommunication.Models;
using CommunityToolkit.Mvvm.Input;

namespace MultiCommunication.ViewModels
{
    public partial class LogViewModel : ObservableObject
    {
        private readonly WpfLogTarget _logTarget;

        [ObservableProperty]
        public ObservableCollection<LogEntry> logs = new ObservableCollection<LogEntry>();

        public LogViewModel()
        { 
            // 初始化自定义NLog目标
            _logTarget = new WpfLogTarget();

            var config = new LoggingConfiguration();
            config.AddTarget("wpfTarget", _logTarget);
            config.AddRuleForAllLevels(_logTarget); // 记录所有级别的日志
            LogManager.Configuration = config;

            _logTarget.LogEntries.CollectionChanged += LogEntries_CollectionChanged;
        }

        public event Action ScrollToBottomRequested;

        private void LogEntries_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            foreach (LogEntry entry in e.NewItems) 
            {
                Logs.Add(entry);//LogEntries中的元素添加到Logs中
            }
            ScrollToBottomRequested?.Invoke();

        }

        private void ReloadLogs()
        {
            Logs.Clear();
            foreach (var entry in _logTarget.LogEntries)
            {
                Logs.Add(entry);
            }
        }
        [RelayCommand]
        public void SelectInfo()
        {
            LogFilter("Info");
        }

        [RelayCommand]
        public void SelectWarning()
        {
            LogFilter("Warn");
        }

        [RelayCommand]
        public void SelectError()
        {
            LogFilter("Error");
        }
        // 清除日志
        [RelayCommand]
        public void ClearLogs()
        {
            _logTarget.LogEntries.Clear();
        }

        private void LogFilter(string level)
        {
            Logs.Clear();
            foreach (var entry in _logTarget.LogEntries)
            {
                if (entry.Level == level && _logTarget.LogEntries.Count != 0)
                {
                    Logs.Add(entry);
                }
            }
        }

    }
}
